#include "preHeader.h"
#include "StoryHook.h"
#include "MapInstance.h"

StoryHook::StoryHook(MapInstance* pMapInstance)
: IMapHook(pMapInstance)
{
}

StoryHook::~StoryHook()
{
}

void StoryHook::InitLuaEnv()
{
	IMapHook::InitLuaEnv();

	auto L = m_pMapInstance->L;
	lua::class_add<StoryHook>(L, "StoryHook");
	lua::class_inh<StoryHook, IMapHook>(L);
	lua::class_def<StoryHook>(L, "FinishPlayStory", &StoryHook::FinishPlayStory);

	LuaTable t(L, "HookTimerType");
	t.set("PlayTimeout", HookTimerType::PlayTimeout);
	t.set("DelayStage", HookTimerType::DelayStage);

	static const std::string scriptFile = "scripts/Hook/story.lua";
	RunScriptFile(L, scriptFile, m_pMapInstance, this);
}

void StoryHook::InitPlayArgs(const std::string_view& args)
{
	ConstNetBuffer tpArgs(args.data(), args.size());
	uint32 questTypeID, mapType;
	tpArgs >> questTypeID >> mapType;

	char buffer[PATH_MAX];
	snprintf(buffer, sizeof(buffer),
		"scripts/Story/%d.lua", 1000000 + questTypeID);
	auto L = m_pMapInstance->L;
	sLuaMgr.DoFile(L, buffer);
	m_variables.Get<LuaTable>().get<LuaFunc>("init").Call<void,
		const LuaTable&>(LuaTable(L, "cfg"), questTypeID, mapType);
}

void StoryHook::Play()
{
	auto L = m_pMapInstance->L;
	m_variables.Get<LuaTable>().get<LuaFunc>("play").Call<void>();
}

void StoryHook::FinishPlayStory(bool isSucc,
	uint32 questTypeID, uint32 backMapType, uint32 delayLeaveMS)
{
	m_pMapInstance->PlayGameOver();
	for (auto&[guid, pPlayer] : m_pMapInstance->GetPlayerStorageMap()) {
		pPlayer->GetQuestStorage()->OnPlayStory(questTypeID, isSucc);
		pPlayer->CreateTimerX([=]() {
			pPlayer->TeleportTo(
				MakeInstGuid(backMapType, pPlayer->GetMapId()),
				{ pPlayer->GetPosition(), pPlayer->GetOrientation() });
		}, delayLeaveMS, 1);
	}
}
